package com.yunshipei.ui.fragment;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.yunshipei.base.BaseSubscriberAdapter;
import com.yunshipei.common.Globals;
import com.yunshipei.common.manager.EnterConfig;
import com.yunshipei.common.net.HttpMethods;
import com.yunshipei.core.utils.NetUtils;
import com.yunshipei.enterplorer.R;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.model.CollectionData;
import com.yunshipei.model.CollectionItemData;
import com.yunshipei.model.CollectionTag;
import com.yunshipei.model.YspEvent;
import com.yunshipei.ui.dialog.DialogHelper;
import com.yunshipei.ui.dialog.WaitDialog;
import com.yunshipei.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnItemClick;
import butterknife.OnItemLongClick;
import io.rong.eventbus.EventBus;

public class CollectionFragment extends Fragment {

    private Context mContext;

    private List<CollectionItemData> mCollections = new ArrayList<>();
    private CollectionListAdapter mAdapter;

    @Bind(R.id.list_view_collection)
    protected ListView mListView;
    @Bind(R.id.fab_collection)
    protected FloatingActionButton mFaBtn;
    @Bind(R.id.iv_collection_header_bg)
    protected ImageView mHeaderBackground;

    private View mEmptyView;
    private View mLoadingView;

    private String mUUID = "";
    private String mCompanyID = "";

    private CollectionShowInteractionListener mCollectionInteractionListener;

    public static CollectionFragment newInstances() {
        return new CollectionFragment();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof CollectionShowInteractionListener) {
            mCollectionInteractionListener = (CollectionShowInteractionListener) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mCollectionInteractionListener = null;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        this.mContext = getActivity();
        SharedPreferences sp = YspPreferences.getInstance().getSharedPreferences();
        this.mUUID = sp.getString(Globals.UUID, "");
        this.mCompanyID = mContext.getSharedPreferences(Globals.NO_CLEAR_SHP, Context.MODE_PRIVATE).getString(Globals.SP_COMPANY_ID, "");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_collection_show, container, false);
        ButterKnife.bind(this, view);
        mEmptyView = inflater.inflate(R.layout.empty_view_collection, container, false);
        mLoadingView = inflater.inflate(R.layout.loading_view_collection, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        switch (EnterConfig.getInstance().getThemeCode()) {
            case "1":
                mHeaderBackground.setImageResource(R.drawable.collection_background_red);
                break;
            case "2":
                mHeaderBackground.setImageResource(R.drawable.collection_background_blue);
                break;
            case "3":
                mHeaderBackground.setImageResource(R.drawable.collection_background_purple);
                break;
            case "4":
                mHeaderBackground.setImageResource(R.drawable.collection_background_green);
                break;
            case "5":
                mHeaderBackground.setImageResource(R.drawable.collection_background_orange);
                break;
            case "6":
                mHeaderBackground.setImageResource(R.drawable.collection_background_black);
                break;
            default:
                mHeaderBackground.setImageResource(R.drawable.collection_background_red);
        }
        mFaBtn.setBackgroundColor(EnterConfig.getInstance().getGlobalColor());
        mFaBtn.setBackgroundTintList(ColorStateList.valueOf(EnterConfig.getInstance().getGlobalColor()));
        ((ViewGroup) mListView.getParent()).addView(mLoadingView);
        ((ViewGroup) mListView.getParent()).addView(mEmptyView);
        mListView.setEmptyView(mLoadingView);
        mListView.setEmptyView(mEmptyView);
        mEmptyView.setVisibility(View.INVISIBLE);
        mAdapter = new CollectionListAdapter(mContext, mCollections);
        mListView.setAdapter(mAdapter);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!NetUtils.isNetworkAvailable(mContext)) {
            mEmptyView.setVisibility(View.VISIBLE);
            mLoadingView.setVisibility(View.INVISIBLE);
            ToastUtils.showToast(R.string.net_no_connect);
            return;
        }
        HttpMethods.getInstance().getCollection(mCompanyID, mUUID, new BaseSubscriberAdapter<CollectionData>() {
            @Override
            public void onNext(CollectionData collectionData) {
                if (collectionData.status == 1) {
                    mLoadingView.setVisibility(View.INVISIBLE);
                    List<CollectionItemData> collectionItemDatas = collectionData.collectionItemData;
                    if (collectionItemDatas != null && collectionItemDatas.size() > 0) {
                        mCollections.addAll(collectionItemDatas);
                        mAdapter.notifyDataSetChanged();
                    } else {
                        mEmptyView.setVisibility(View.VISIBLE);
                    }
                } else {
                    onError(collectionData.message);
                }
                fetchStarDataFinish = true;
            }

            @Override
            public void onError(String errorMessage) {
                mLoadingView.setVisibility(View.INVISIBLE);
                mEmptyView.setVisibility(View.VISIBLE);
                ToastUtils.showToast(getString(R.string.pull_collection_error));
                fetchStarDataFinish = true;
            }
        });
    }

    private boolean fetchStarDataFinish = false;

    @OnClick(R.id.fab_collection)
    protected void fabBtnClick() {
        if (fetchStarDataFinish) {
            if (canCollection) {
                CollectionTag collectionTag = (CollectionTag) mFaBtn.getTag();
                if (collectionTag.hasCollected) {
                    //已经收藏，删除收藏
                    deleteCollection(collectionTag.collectionItemData, true);
                } else {
                    //没有收藏，添加收藏
                    addCollection(collectionTag.collectionItemData, true);
                }
            } else {
                ToastUtils.showToast("该页面不支持收藏...");
            }
        } else {
            ToastUtils.showToast("正在拉取收藏数据，请稍候再试...");
        }
    }

    @OnItemClick(R.id.list_view_collection)
    protected void listViewItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        CollectionItemData data = mCollections.get(position);
        mCollectionInteractionListener.onCollectionItemClick(data.url);
    }

    @OnItemLongClick(R.id.list_view_collection)
    protected boolean listViewItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        final CollectionItemData collectionItemData = mCollections.get(position);
        DialogHelper.showDeleteCollectionDialog(mContext, collectionItemData.title, new CancelCollectionCallBack() {
            @Override
            public void removeCollection() {
                deleteCollection(collectionItemData, true);
            }
        });
        return true;
    }

    private boolean canCollection = false;

    //如果滑动从浏览器，则更新新标状态
    public void updateStarState(CollectionItemData collectionData) {
        CollectionTag collectionTag = null;
        if (collectionData == null) {
            canCollection = false;
            mFaBtn.setImageResource(R.drawable.start_uncollect);
        } else {
            canCollection = true;
            Boolean hasCollected = hasCollected(collectionData);
            mFaBtn.setImageResource(hasCollected ? R.drawable.start_already_collect : R.drawable.start_uncollect);
            collectionTag = new CollectionTag(hasCollected, collectionData);
        }
        mFaBtn.setTag(collectionTag);
    }

    private Boolean hasCollected(CollectionItemData collectionData) {
        for (CollectionItemData collectionItemData : mCollections) {
            if (collectionItemData.url.equals(collectionData.url)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 浏览器菜单栏的收藏按钮点击事件
     */
    public void onEventMainThread(YspEvent.CollectionApp collectionApp) {
        if (fetchStarDataFinish) {
            CollectionItemData collectionItemData = collectionApp.collectionDataItem;
            if (hasCollected(collectionItemData)) {
                //已经收藏，移除收藏
                deleteCollection(collectionItemData, false);
            } else {
                //没有收藏，添加收藏
                addCollection(collectionItemData, false);
            }
        } else {
            ToastUtils.showToast("正在拉取收藏数据，请稍候在试...");
        }
    }

    /**
     * 添加收藏
     *
     * @param collectionItemData 收藏数据
     * @param leftDrawer         是否是左侧抽屉的添加收藏点击事件
     */
    private void addCollection(final CollectionItemData collectionItemData, final boolean leftDrawer) {
        if (!NetUtils.isNetworkAvailable(mContext)) {
            ToastUtils.showToast(R.string.net_no_connect);
            return;
        }
        final WaitDialog waitDialog = DialogHelper.getNoCancelableWaitDialog(mContext, "正在添加收藏，请稍候...");
        waitDialog.show();
        HttpMethods.getInstance().addCollection(mCompanyID, mUUID, object2Json(collectionItemData), new BaseSubscriberAdapter<JSONObject>() {
            @Override
            public void onNext(JSONObject jsonObject) {
                waitDialog.dismiss();
                int status = jsonObject.optInt(Globals.YSP_INTER_STATUE);
                if (1 == status) {
                    mEmptyView.setVisibility(View.INVISIBLE);
                    mLoadingView.setVisibility(View.INVISIBLE);
                    mCollections.add(collectionItemData);
                    mAdapter.notifyDataSetChanged();
                    if (leftDrawer) {
                        mFaBtn.setImageResource(R.drawable.start_already_collect);
                        mFaBtn.setTag(new CollectionTag(true, collectionItemData));
                    }
                    ToastUtils.showToast(leftDrawer ? getString(R.string.add_collection_success) : getString(R.string.collection_has_done));
                } else {
                    ToastUtils.showToast(getString(R.string.add_collection_failure));
                }
            }

            @Override
            public void onError(String errorMessage) {
                waitDialog.dismiss();
                ToastUtils.showToast(errorMessage);
            }
        });
    }

    /**
     * 移除收藏
     *
     * @param collectionItemData 收藏数据的model
     * @param leftDrawer         是否是左侧抽屉中的收藏
     */
    private void deleteCollection(final CollectionItemData collectionItemData, final boolean leftDrawer) {
        if (!NetUtils.isNetworkAvailable(mContext)) {
            ToastUtils.showToast(R.string.net_no_connect);
            return;
        }
        final WaitDialog waitDialog = DialogHelper.getNoCancelableWaitDialog(mContext, "正在取消收藏，请稍候...");
        waitDialog.show();
        HttpMethods.getInstance().deleteCollection(mCompanyID, mUUID, object2Json(collectionItemData), new BaseSubscriberAdapter<JSONObject>() {
            @Override
            public void onNext(JSONObject jsonObject) {
                waitDialog.dismiss();
                int status = jsonObject.optInt(Globals.YSP_INTER_STATUE);
                if (1 == status) {
                    for (CollectionItemData collectionItem : mCollections) {
                        if (collectionItem.url.equals(collectionItemData.url)) {
                            mCollections.remove(collectionItem);
                            mAdapter.notifyDataSetChanged();
                            if (leftDrawer) {
                                CollectionTag collectionTag = (CollectionTag) mFaBtn.getTag();
                                if (collectionTag != null) {
                                    CollectionItemData itemData = collectionTag.collectionItemData;
                                    if (collectionTag.hasCollected && itemData.url.equals(collectionItemData.url)) {
                                        mFaBtn.setImageResource(R.drawable.start_uncollect);
                                        mFaBtn.setTag(new CollectionTag(false, collectionItemData));
                                    }
                                } else {
                                    mFaBtn.setImageResource(R.drawable.start_uncollect);
                                    mFaBtn.setTag(null);
                                }
                            }
                            break;
                        }
                    }
                    if (mCollections.size() == 0) {
                        mEmptyView.setVisibility(View.VISIBLE);
                    }
                    ToastUtils.showToast(getString(R.string.delete_collection_success));
                } else {
                    ToastUtils.showToast(getString(R.string.delete_collection_failure));
                }
            }

            @Override
            public void onError(String errorMessage) {
                waitDialog.dismiss();
                ToastUtils.showToast(errorMessage);
            }
        });
    }

    private String object2Json(CollectionItemData data) {
        String result = "";
        JSONObject object = new JSONObject();
        try {
            object.put("url", data.url);
            object.put("iconUrl", data.imageUrl);
            object.put("title", data.title);
            result = object.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return result;
    }

    private static class CollectionListAdapter extends BaseAdapter {
        private Context context;
        private List<CollectionItemData> list;

        private CollectionListAdapter(Context context, List<CollectionItemData> list) {
            this.context = context;
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public CollectionItemData getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.list_collection_show_item, parent, false);
                viewHolder = new ViewHolder();
                viewHolder.title = (TextView) convertView.findViewById(R.id.collection_item_title);
                viewHolder.icon = (ImageView) convertView.findViewById(R.id.collection_icon);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            CollectionItemData data = getItem(position);
            viewHolder.title.setText(data.title);
            String img = data.imageUrl;
            if (!TextUtils.isEmpty(img)) {
                Glide.with(context).load(img).placeholder(R.drawable.collect_default_icon).into(viewHolder.icon);
            } else {
                Glide.with(context).load(R.drawable.collect_default_icon).into(viewHolder.icon);
            }
            return convertView;
        }

        private static class ViewHolder {
            private TextView title;
            private ImageView icon;
        }
    }

    public interface CollectionShowInteractionListener {
        void onCollectionItemClick(String url);
    }

    public interface CancelCollectionCallBack {
        void removeCollection();
    }
}
